<template>
  <div>
    <div class="container">
      <PublicSearch @getSearchChangeData="getSearchChangeData" />
    </div>
    <div class="container">
      <div class="table-table">
        <BiTable
          :loading="tableLoading"
          :data="tableData"
          size="medium"
          fixed="sticky"
          fixed-offset="50"
          :column="tableColumn"
          :show-summary="true"
          :summary-method="getSummaries"
          :auto-scroll="false"
          :header-cell-style="headerCellStyle"
        ></BiTable>
      </div>
    </div>
  </div>
</template>

<script lang="jsx">
import moment from 'moment'
import { numberFormatThousandthPercentile, numFormat } from '@/utils/index'
import PublicSearch from './publicSearch.vue'
import { chapterAnalysis } from '@/api/content'
export default {
  components: { PublicSearch },
  props: ['totalnum'],
  data() {
    return {
      fieldContrast: true,
      formData: {
        chapter_id: '',
        type: '',
        pay_template_id: '',
        mini_app_id: localStorage.getItem('mini_app_id')
      },
      date: [moment().subtract(14, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      detailHourList: [],
      chapterAnalysisChartLoading: false,
      chapterAnalysisChartData: {
        firstField: [],
        secondField: []
      },
      chapter_num: '1',
      detailHourChartLoading: false,
      tableLoading: false,
      tableData: [],
      tableColumn: [
        { prop: 'chapter_num', align: 'left',
          renderHeader: (h, { row }) => {
            return (<div style={'text-align:left;'}>
                剧集
            </div>)
          },
          minWidth: 90,
          render: (h, { row }) => {
            return (
              <div>第{row.chapter_num}集</div>
            )
          }
        },
        { prop: 'duration', minWidth: 70,
          align: 'left',
          renderHeader: (h, { row }) => {
            return (<div style={'text-align:left;'}>
                时长
            </div>)
          },
          render: (h, { row }) => {
            return (
              <span>{this.formatTime(row.duration)}</span>
            )
          }
        },
        { label: 'UV', prop: 'read_member', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{this.formatNumber(row.read_member)}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'进入该集的人数 =（观看人数+模版唤起人数）的去重'} placement={'top'}>
              <span>UV</span>
            </el-tooltip>)
          }
        },
        { label: '观看人数', prop: 'effective_read_member', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{this.formatNumber(row.effective_read_member)}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'该集观看时长>0秒的人数，包括埋点时长=0的人数'} placement={'top'}>
              <span>观看人数</span>
            </el-tooltip>)
          }
        },
        { label: '有效观看人数', prop: 'three_read_member', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{this.formatNumber(row.three_read_member)}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'该集观看时长≥3秒的人数'} placement={'top'}>
              <span>有效观看人数</span>
            </el-tooltip>)
          }
        },
        { label: '完播人数', prop: 'broadcasting_member', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{this.formatNumber(row.broadcasting_member)}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'观看时⻓ > 此集时⻓ - 20秒'} placement={'top'}>
              <span>完播人数</span>
            </el-tooltip>)
          }
        },
        { label: '流失人数', prop: 'lost_member', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{this.formatNumber(row.lost_member)}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'看过本集但没有看过下一集的人数'} placement={'top'}>
              <span>流失人数</span>
            </el-tooltip>)
          }
        },
        { label: 'UV留存率', prop: 'uvlc', width: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{ isNaN((row.uvlc + '') * 1) || ((row.uvlc + '').indexOf('Infinity') != -1) ? '100.00%' : row.uvlc + '%'}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'本集UV/上集UV'} placement={'top'}>
              <span>UV留存率</span>
            </el-tooltip>)
          }
        },
        { label: 'UV流失率', prop: 'uvls', width: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{ isNaN(Number(row.uvls)) || ((row.uvls + '').indexOf('Infinity') != -1) ? '0.00%' : row.uvls + '%'}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'（本集UV-下集UV）/本集UV'} placement={'top'}>
              <span>UV流失率</span>
            </el-tooltip>)
          }
        },
        { label: '留存率', prop: 'retention_roi', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{row.retention_roi + '%'}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'看过本集且看过下集的人数/本集的观看人数'} placement={'top'}>
              <span>留存率</span>
            </el-tooltip>)
          }
        },
        { label: '流失率', prop: 'turnover_roi', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{row.turnover_roi + '%'}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'看过本集但没有看过下一集的人数/本集的观看人数'} placement={'top'}>
              <span>流失率</span>
            </el-tooltip>)
          }
        },
        { label: '完播率', prop: 'completion_roi', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{row.completion_roi + '%'}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'完播人数/观看人数'} placement={'top'}>
              <span>完播率</span>
            </el-tooltip>)
          }
        },
        { label: '追剧人数', prop: 'click_member', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{this.formatNumber(row.click_member)}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'点击追剧按钮的人数'} placement={'top'}>
              <span>追剧人数</span>
            </el-tooltip>)
          }
        },
        { label: '唤起模板人数', prop: 'tell_member', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{this.formatNumber(row.tell_member)}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} placement={'top'}>
              <div slot='content' style={{ maxWidth: '300px' }}>
                  唤起模板人数是从2023年11月8日以后开始统计数据
              </div>
              <span>唤起模板人数</span>
            </el-tooltip>)
          }
        },
        { label: '支付人数', prop: 'pay_member', minWidth: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{this.formatNumber(row.pay_member)}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'此集支付人数'} placement={'top'}>
              <span>支付人数</span>
            </el-tooltip>)
          }
        },
        { label: '唤起模板用户支付率', prop: 'pay_roi', width: 110, align: 'right',
          render: (h, { row }) => {
            return (
              <span>{row.pay_roi + '%'}</span>
            )
          },
          renderHeader: (h, { row }) => {
            return (<el-tooltip effect={'dark'} content={'该集支付人数/模版唤起人数'} placement={'top'}>
              <span>唤起模板用户支付率</span>
            </el-tooltip>)
          }
        }

      ],
      headerCellStyle: {
        color: '#333333',
        fontWeight: 500,
        textAlign: 'right'
      },
      totalDataNum: [],
      columnChartList: [],
      columnList: []
    }
  },
  computed: {
    playlet_id() {
      return this.$route.query.playlet_id || ''
    },
    hourSelectList() {
      const hourSelect = []
      for (let i = 1; i <= this.totalnum; i++) {
        hourSelect.push({
          label: '第' + (i) + '集',
          value: (i) + ''
        })
      }
      return hourSelect
    }
  },
  mounted() {
    this.getChapterAnalysisListData()
  },
  methods: {

    // 付费模板

    // 模板类型

    async getChapterAnalysisListData() {
      this.tableLoading = true
      const time = {
        start: this.date[0] ? this.date[0] : '',
        end: this.date[1] ? this.date[1] : ''
      }
      const res = await chapterAnalysis({ condition: this.formData, playlet_id: this.playlet_id, date: time })

      if (res.status_code === 1) {
        let duration = 0
        let read_member = 0
        let effective_read_member = 0
        let broadcasting_member = 0
        let lost_member = 0
        let click_member = 0
        let tell_member = 0
        let pay_member = 0
        let three_read_member_num = 0

        let uvlc = 0 // uv留存率：本集观看人数/上集观看人数
        let uvls = 0 // uv流失率：（本集观看人数-下一集观看人数）/本集观看人数
        let last_read_member = 0 // 上集观看人数
        let next_read_member = 0 // 下集观看人数

        this.tableData = res.data.map((item, index) => {
          duration += Number(item.duration)
          read_member += Number(item.read_member)
          effective_read_member += Number(item.effective_read_member)
          broadcasting_member += Number(item.broadcasting_member)
          lost_member += Number(item.lost_member)
          click_member += Number(item.click_member)
          tell_member += Number(item.tell_member)
          pay_member += Number(item.pay_member)
          three_read_member_num += Number(item.three_read_member)
          const turnover_roi = Number(item.effective_read_member) !== 0 ? Number(item.lost_member) / Number(item.effective_read_member) : 0 // 流失率
          const retention_roi = 1 - turnover_roi // 留存率
          const completion_roi = Number(item.effective_read_member) !== 0 ? Number(item.broadcasting_member) / Number(item.effective_read_member) : 0 // 完播率
          const pay_roi = Number(item.tell_member) !== 0 ? Number(item.pay_member) / Number(item.tell_member) : 0 // 完播率
          next_read_member = index < res.data.length - 1 ? res.data[index + 1].read_member : 0
          //  uv留存率：本集观看人数/上集观看人数
          //  uv流失率：（本集观看人数-下一集观看人数）/本集观看人数
          if (index !== 0) {
            uvlc = (Number(item.read_member) / last_read_member)
          } else {
            uvlc = 1
          }
          last_read_member = Number(item.read_member)

          if (index < res.data.length - 1) {
            uvls = ((Number(item.read_member) - next_read_member) / Number(item.read_member))
          } else {
            uvls = 1
          }
          return { ...item, turnover_roi: (turnover_roi * 100).toFixed(2), retention_roi: (retention_roi * 100).toFixed(2), completion_roi: (completion_roi * 100).toFixed(2), pay_roi: (pay_roi * 100).toFixed(2), uvlc: (uvlc * 100).toFixed(2), uvls: (uvls * 100).toFixed(2) }
        })

        const turnover_roi_t = Number(effective_read_member) !== 0 ? Number(lost_member) / Number(effective_read_member) : 0 // 流失率
        const retention_roi_t = 1 - turnover_roi_t // 留存率
        const completion_roi_t = Number(effective_read_member) !== 0 ? Number(broadcasting_member) / Number(effective_read_member) : 0 // 完播率
        const pay_roi_t = Number(tell_member) !== 0 ? Number(pay_member) / Number(tell_member) : 0 // 完播率

        this.totalDataNum = {
          chapter_num: '汇总',
          duration: this.formatTime(duration),
          read_member,
          effective_read_member,
          broadcasting_member,
          lost_member,
          retention_roi: (retention_roi_t * 100).toFixed(2),
          turnover_roi: (turnover_roi_t * 100).toFixed(2),
          completion_roi: (completion_roi_t * 100).toFixed(2),
          click_member,
          tell_member,
          pay_member,
          pay_roi: (pay_roi_t * 100).toFixed(2),
          uvlc: '',
          uvls: '',
          three_read_member: three_read_member_num
        }
      }
      this.tableLoading = false
    },
    getSummaries(column) {
      const { columns } = column
      const sum = []
      columns.forEach((item, index) => {
        if (index === 0) {
          sum[0] = '汇总'
          return
        }
        if (Object.prototype.hasOwnProperty.call(this.totalDataNum, item.property)) {
          if (item.property === 'retention_roi' || item.property === 'turnover_roi' || item.property === 'completion_roi' || item.property === 'pay_roi') {
            sum[index] = this.totalDataNum[item.property] + '%'
          } else if (item.property === 'duration') {
            sum[index] = this.totalDataNum[item.property]
          } else {
            sum[index] = this.formatNumber(this.totalDataNum[item.property])
          }
        } else {
          return
        }
      })
      // console.log(this.totalDataNum)
      return sum
    },
    formatNumber(data) {
      return numberFormatThousandthPercentile(data)
    },
    formatNumber1(data) {
      return numFormat(data)
    },
    formatTime(seconds) {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const remainingSeconds = seconds % 60

      let time = ''

      if (hours > 0) {
        time += hours.toString().padStart(2, '0') + ':'
      }

      time += minutes.toString().padStart(2, '0') + ':'
      time += remainingSeconds.toString().padStart(2, '0')

      return time
    },
    clickColChart(data) {
      this.chapter_num = data + ''
      this.$nextTick(() => {
        this.getChapterAnalysisChartDetails()
      })
    },
    getSearchChangeData(data) {
      this.formData = {
        chapter_id: data.chapter_id,
        type: data.type,
        pay_template_id: data.pay_template_id,
        mini_app_id: localStorage.getItem('mini_app_id')
      }
      this.date = data.regDate
      this.getChapterAnalysisListData()
    },
    getChapterAnalysisChartDetailData() {
      this.getChapterAnalysisChartDetails()
      this.getChapterAnalysisListData()
    },
    getSearchChangeDataTemplate() {
      this.$set(this.formData, 'pay_template_id', [])
      this.$set(this.formData, 'templateType', '')
      this.formData.pay_template_id = []
      this.formData.templateType = ''
      this.$set(this.formData, 'coporation_id', [])
      this.$set(this.formData, 'advertiser_id', [])
      this.formData.coporation_id = []
      this.formData.advertiser_id = ''
      // this.$nextTick(() => {
      //   this.getSearchChangeData()
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background: #fff;
  padding: 20px 20px 0;
  border-radius: 2px;
}
.container + .container {
  margin-top: 10px;
  padding: 20px;
}
.chart-title {
  display: flex;
  align-items: center;

  svg {
    margin-right: 5px;
  }
  span {
    font-size: 18px;
    font-weight: 500;
    color: #333333;
    line-height: 25px;
  }
}

.search-form {
  .search-item {
    width: 330px !important;
    padding-bottom: 20px !important;
    &:last-of-type {
      padding-right: 0;
    }
  }
}
.field-container {
  margin-top: 20px;
}
</style>